/**
Company: Sarkar software technologys
WebSite: http://www.sarkar.cn
Author: yeganaaa
Date : 10/31/17
Time: 12:00 PM
 */

package Cn.Sarkar.SimplePipeLineServer.Core.Entities

class ActionPath(path: String) {
    private val paths = ArrayList<String>()
    operator fun get(index: Int) = paths[index]
    fun getLast() = paths[paths.lastIndex]
    operator fun set(index: Int, value: String){
        if (value.contains("/")) throw Exception("Syntax error Path string.")
        paths[index] = value
    }
    fun getAll() = paths.toTypedArray()
    operator fun contains(value: String) = paths.contains(value)

    init {

        var isSplitChar = false
        path.forEach {
            if (isSplitChar && it == '/') throw Exception("Syntax error Path string.")
            isSplitChar = it == '/'
        }

        var path = if (path.startsWith("/")) path.removeRange(0, 1) else path
        path = if (path.endsWith("/")) path.removeRange(path.length - 1, path.length) else path


        if (path != "") paths.addAll(path.split("/"))
    }
    fun insert(index: Int, path: String){
        paths.add(index, path)
    }
    fun insertToBegin(path: String){
        insert(0, path)
    }
    fun insertToEnd(path: String)
    {
        insert(paths.size, path)
    }
    fun remove(index: Int)
    {
        paths.removeAt(index)
    }
    fun removeFromFirst(){
        paths.removeAt(0)
    }
    fun removeFromLast(){
        paths.removeAt(paths.lastIndex)
    }
    operator fun plus(path: ActionPath) = ActionPath("").apply {
        paths.addAll(this@ActionPath.paths)
        paths.addAll(path.paths)
    }
    override fun toString() = "/" + paths.joinToString("/")
}